package homework;


import java.util.*;

public class HomeTest02 {
    //2.使用HashSet和TreeSet存储多个商品信息，遍历并输出；其中商品属性：编号，名称，单价，出版社；要求向其中添加多个相同的商品，验证集合中元素的唯一性。
    //提示：向HashSet中添加自定义类的对象信息，需要重写hashCode和equals( )
    //	 向TreeSet中添加自定义类的对象信息，需要实现Comparable接口，指定比较规则
    public static void main(String[] args) {
        Set<Book1> books = new HashSet<>();
        books.add(new Book1("1","java",100,"清华大学"));
        books.add(new Book1("1","java",100,"清华大学"));
        books.add(new Book1("2","c++",200,"北京大学"));
        books.forEach(book -> System.out.println(book));

        Set<Book1> books1 = new TreeSet<>(new Comparator<Book1>() {
            @Override
            public int compare(Book1 o1, Book1 o2) {
                if (o1.getId().equals(o2.getId())) {//判断id是否相等
                    return o1.getName().compareTo(o2.getName());//比较名称
                }else {
                    return o1.getId().compareTo(o2.getId());
                }
            }
        });
        books1.add(new Book1("1","java",100,"清华大学"));
        books1.add(new Book1("1","语文",200,"清华大学"));
        books1.add(new Book1("2","c++",200,"北京大学"));
        books1.forEach(book -> System.out.println(book));

    }
}
class Book1{
    private String id;
    private String name;
    private double price;
    private String press;
    public Book1(String id, String name, double price, String press) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.press = press;
    }

    public Book1() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getPress() {
        return press;
    }

    public void setPress(String press) {
        this.press = press;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book1 Book1 = (Book1) o;
        return Double.compare(Book1.price, price) == 0 && Objects.equals(id, Book1.id) && Objects.equals(name, Book1.name) && Objects.equals(press, Book1.press);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, price, press);
    }

    @Override
    public String toString() {
        return "编号："+id+"  名称："+name+"  单价："+price+"  出版社："+press;
    }
}